package com.ishang.vm.controller;

import com.ishang.vm.pojo.PartyMember;
import com.ishang.vm.result.Result;
import com.ishang.vm.result.ResultFactory;
import com.ishang.vm.service.PartyMemberService;
import com.ishang.vm.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;


@RestController
public class PartyMemberController {
    @Autowired
    PartyMemberService partyMemberService;

    @GetMapping("/api/members")
    public List<PartyMember> list() throws Exception {
        return partyMemberService.list();
    }

    @PutMapping("/api/admin/partymember/members")
    public Result addOrUpdate(@RequestBody PartyMember partyMember) throws Exception {
        if (partyMemberService.addOrUpdate(partyMember))
            return ResultFactory.buildSuccessResult("修改成功");
        ;
        return ResultFactory.buildFailResult("参数错误，删除失败");
    }

    @PutMapping("/api/admin/partymember/members/delete")
    public void delete(@RequestBody PartyMember partyMember) throws Exception {
        partyMemberService.deleteById(partyMember.getId());
    }

    @GetMapping("/api/search/pm")
    public List<PartyMember> searchResult(@RequestParam("keywords") String keywords) {
        // 关键字为空时，查出所有居住人口
        if ("".equals(keywords)) {
            return partyMemberService.list();
        } else {
            return partyMemberService.Search(keywords);
        }
    }

    @PostMapping("/api/admin/partymember/members/photos")
    public String coversUpload(MultipartFile file) throws Exception {
        //String folder = "E:\\Java\\SpringBoot\\HW\\tempimg";
        String folder = "C:/vm/img";
        File imageFolder = new File(folder);
        File f = new File(imageFolder, StringUtils.getRandomString(6) + file.getOriginalFilename()
                .substring(file.getOriginalFilename().length() - 4));
        if (!f.getParentFile().exists())
            f.getParentFile().mkdirs();
        try {
            file.transferTo(f);
            String imgURL = "http://139.224.2.57:8443/api/file/" + f.getName();
            return imgURL;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
}
